# coding:utf8
import requests
import json, urllib
import pycurl, StringIO

requests = requests.Session()


def curl(url):
    global requests
    head = {
        "Cookie": "pspt=%7B%22id%22%3A%2211673%22%2C%22pswd%22%3A%226a95eb9b29f19f0c9f54e195aa3d01ac%22%2C%22_code%22%3A%2242600ca418a81575ce42dc8017af2b54%22%7D; pgv_pvi=9410215936; pgv_si=s9764569088",
        "Host": "app.qichacha.com", "Accept": "*/*",
        "User-Agent": "EnterpriseSearch/8.0.0 (iPhone; iOS 9.0.2; Scale/2.00)",
        "token": "f8e0d2e71cecb8f94b9eef7b492f8ee2"}
    return requests.get(url, headers=head).content


# def curl(url):  #关联企业
#     head = ["Host:app.qichacha.com","Accept*/*","User-Agent:EnterpriseSearch/8.0.0 (iPhone; iOS 9.0.2; Scale/2.00)","token:f8e0d2e71cecb8f94b9eef7b492f8ee2"]
#
#     c = pycurl.Curl()
#     c.setopt(pycurl.VERBOSE,1)
#     c.setopt(pycurl.FOLLOWLOCATION, 1)
#     c.setopt(pycurl.MAXREDIRS, 5)
#     c.setopt(pycurl.COOKIEJAR, "cookie_file_name")
#     c.setopt(pycurl.COOKIEFILE, "cookie_file_name")
#
#     c.setopt(pycurl.CONNECTTIMEOUT, 60)
#     c.setopt(pycurl.TIMEOUT, 300)
#
#     c.setopt(pycurl.HTTPPROXYTUNNEL,1)
#     c.fp = StringIO.StringIO()
#     c.setopt(pycurl.HTTPHEADER,head)
#     c.setopt(pycurl.URL,url)
#     c.setopt(c.WRITEFUNCTION, c.fp.write)
#     c.perform()
#     return c.fp.getvalue()
def search(company):
    url = 'http://app.qichacha.com/enterprises/new/i1/cloudSearch?key=%s&province=&token=11e66f45f3502af0c4a7278614569364' % urllib.quote(
        company)
    print url
    company_lsit = curl(
        'http://app.qichacha.com/enterprises/new/i1/cloudSearch?key=%s&province=&token=11e66f45f3502af0c4a7278614569364' % urllib.quote(
            company))
    print company_lsit

    for i in company_lsit['data']['Result']:
        keyId = i['KeyNo']
        detail_html = curl(
            'http://app.qichacha.com/enterprises/new/i1/getData?unique=%s&token=1f62856ebea80bf6b7b6054233056a91' % keyId)
        year_report = curl(
            'http://app.qichacha.com/enterprises/new/i1/getAnnualReportList?unique=%s&token=1f62856ebea80bf6b7b6054233056a91' % keyId)
        result = {'basic': detail_html, 'year_report': year_report}
        return result


print json.dumps(search('北京进取新技术有限公司'), ensure_ascii=False, indent=4)
